#include "utils.hpp"
#include <iostream>
#include <cmath>
string strip_spaces(string& str)
{
	size_t pos;
	while((pos = str.find(" ")) != string::npos) {
		str.replace(pos,1,"");
	}
	return str;
}

unsigned countInstances(string str, char c)
{
	unsigned counter=0;
	char quote;
	for(unsigned i=0;i<str.size();i++) {
		counter += (str[i]==c);
		if(str[i]=='"' || str[i]=='`' || str[i]=='\'') {
			quote = str[i];
			unsigned j;
			for(j=1;j<str.size();j++) {
				if(str[j]=='\\') {
					if(j+1 != str.size()) {
						if(str[j+1]==quote) {
							// Do NOT escape
							j++;
						}
					}
				} else if(str[j]==str[0]) {
					// It's the end of the quote, break
					break;
				}
			}
			i=j;
		}
	}
	return counter;
}

int charToInt(char c) {
	if(c >= '0' && c <= '9') return (c-'0');
	if(c == 'a' || c == 'A') return 10;
	if(c == 'b' || c == 'B') return 11;
	if(c == 'c' || c == 'C') return 12;
	if(c == 'd' || c == 'D') return 13;
	if(c == 'e' || c == 'E') return 14;
	if(c == 'f' || c == 'F') return 15;
	return 0;
}

double strToDouble(string str, int base)
{
	// Assume that the input string is well-formed
	// The lexer will handle that.
	if(base != 10 && base != 2 && base != 8 && base != 16) return 0;
	double ret = 0;
	int mantissa = 0;
	
	for(unsigned i=0;i<str.size();i++) {
		if(str[i] == '.') {
			mantissa = 1;
		} else {
			
			if(mantissa != 0) {
				// We're "below" the mantissa
				ret += charToInt(str[i]) * pow((double)base,-mantissa);
				mantissa++;
			} else {
				// We're still "above" the mantissa
				ret *= base;
				ret += charToInt(str[i]);
			}
		}
	}
			
	return ret;
}
